package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.RoleMapper;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void delete(Long id) {
        roleMapper.deleteByPrimaryKey(id);

    }

    @Override
    public void save(Role role, Long[] ids) {
        roleMapper.insert(role);
        //往角色权限中间表插入数据
        if (ids != null && ids.length > 0){
            for (Long permissionId : ids) {

                roleMapper.insertRelation(role.getId(),permissionId);
            }
        }

    }

    @Override
    public Role get(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> listAll() {
        return roleMapper.selectAll();
    }

    @Override
    public void update(Role role, Long[] ids) {
        roleMapper.updateByPrimaryKey(role);

        //删除原有关系
        roleMapper.deleteRelation(role.getId());

        //新插入关系
        if (ids != null && ids.length > 0){
            for (Long permissionId : ids) {

                roleMapper.insertRelation(role.getId(),permissionId);
            }
        }

    }

    @Override
    public PageInfo<Role> query(QueryObject qo) {

        /*int totalCount = roleMapper.queryForCount(qo);
        if (totalCount == 0){
            return new PageResult<>(qo.getCurrentPage(), qo.getPageSize(),
                    totalCount, Collections.emptyList());
        }
        //获取总页数
        int totalPage = totalCount % qo.getPageSize()== 0 ?
                totalCount / qo.getPageSize() : totalCount / qo.getPageSize() +1;
        //判断当前页是否大于总页数
        if (qo.getCurrentPage() > totalPage){
            qo.setCurrentPage(totalPage);
        }*/
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Role> roles = roleMapper.queryForList(qo);
        return new PageInfo<>(roles);
    }
}
